<template>
  <view class="face-verify-container">
    <view class="page-header">
      <text class="page-title">实名认证</text>
      <text class="page-desc">请填写真实信息完成身份认证</text>
    </view>
    
    <view class="form-card">
      <uni-forms ref="form" :model="formData" :rules="rules" label-position="top">
        <uni-forms-item label="姓名" name="name">
          <uni-easyinput v-model="formData.name" placeholder="请输入姓名" :clearable="true" />
        </uni-forms-item>
        
        <uni-forms-item label="联系方式" name="contacts">
          <uni-easyinput v-model="formData.contacts" placeholder="请输入联系方式" :clearable="true" type="number" />
        </uni-forms-item>
        
        <uni-forms-item label="身份证号" name="idCardNumber">
          <uni-easyinput v-model="formData.idCardNumber" placeholder="请输入身份证号" :clearable="true" />
        </uni-forms-item>
        
        <uni-forms-item label="人脸照片" name="picUrl">
          <view class="face-photo-wrapper">
            <view class="face-photo-container" @click="openPhotoActionSheet">
              <image v-if="formData.picUrl" :src="formData.picUrl" mode="aspectFill" class="face-photo" />
              <view v-else class="face-photo-placeholder">
                <uni-icons type="camera-filled" size="36" color="#3c9cff"></uni-icons>
                <text class="placeholder-text">点击上传人脸照片</text>
              </view>
            </view>
            <text class="photo-tip">请上传清晰的正面照片，大小不超过1M</text>
          </view>
        </uni-forms-item>
      </uni-forms>
    </view>
    
    <view class="submit-btn-container">
      <button type="primary" @click="submitForm" class="submit-btn">提交认证</button>
    </view>
    
    <!-- 底部操作表 -->
    <uni-popup ref="photoActionSheet" type="bottom">
      <view class="action-sheet">
        <view class="action-sheet-title">选择照片</view>
        <view class="action-item" @click="takePhoto">
          <uni-icons type="camera-filled" size="24" color="#3c9cff"></uni-icons>
          <text>拍照</text>
        </view>
        <view class="action-item" @click="chooseFromAlbum">
          <uni-icons type="image-filled" size="24" color="#3c9cff"></uni-icons>
          <text>从相册选择</text>
        </view>
        <view class="action-item cancel" @click="closeActionSheet">
          <text>取消</text>
        </view>
      </view>
    </uni-popup>
    
    <!-- 使用新的Canvas 2D接口 -->
    <canvas type="2d" id="compressCanvas" style="width: 800px; height: 800px; position: absolute; left: -9999px; top: -9999px; z-index: -1;"></canvas>
  </view>
</template>

<script>
import { idCardPattern, phonePattern } from '@/utils/common'
import { cohabitantDetail, faceVerify } from '@/api/renter'
import { uploadImage } from '@/api/base/index'
import config from '@/config'
import { getToken } from '@/utils/auth'
export default {
  data() {
    return {
      formData: {
        name: '',
        contacts: '',
        idCardNumber: '',
        picUrl: ''
      },
      rules: {
        name: {
          rules: [
            { required: true, errorMessage: '请输入姓名' }
          ]
        },
        contacts: {
          rules: [
            { required: true, errorMessage: '请输入联系方式' },
            { pattern: phonePattern(), errorMessage: '请输入正确的手机号码' }
          ]
        },
        idCardNumber: {
          rules: [
            { required: true, errorMessage: '请输入身份证号' },
            { 
              validateFunction: (rule, value, data, callback) => {
                // 检查是否包含连续的8个*，如果是则免校验
                if (/\*{8}/.test(value)) {
                  callback(); // 通过校验
                } else {
                  // 否则校验身份证格式
                  if (!idCardPattern().test(value)) {
                    callback('请输入正确的身份证号');
                  } else {
                    callback(); // 通过校验
                  }
                }
              }
            }
          ]
        },
        picUrl: {
          rules: [
            { required: true, errorMessage: '请上传人脸照片' }
          ]
        }
      },
      // 图片压缩相关参数
      imageCompressOptions: {
        maxSize: 1024 * 1024, // 1MB
        quality: 0.8 // 初始压缩质量
      },
      // Canvas 2D 上下文
      canvasContext: null
    }
  },
  onReady() {
    // 在页面准备好后获取Canvas 2D上下文
    this.initCanvas();
  },
  onLoad(options) {
    // 如果有回显数据，加载数据
    if (options.renterId) {
      this.getCohabitantDetail(options.renterId);
    } else {
      // 如果有传递的参数，填充表单
      if (options.name) {
        this.formData.name = options.name;
      }
      if (options.contacts) {
        this.formData.contacts = options.contacts;
      }
      if (options.idCardNumber) {
        this.formData.idCardNumber = options.idCardNumber;
      }
    }
  },
  methods: {
    // 初始化Canvas 2D上下文
    initCanvas() {
      const query = uni.createSelectorQuery().in(this);
      query.select('#compressCanvas')
        .fields({ node: true, size: true })
        .exec((res) => {
          if (res[0]) {
            const canvas = res[0].node;
            this.canvasContext = canvas.getContext('2d');
            
            // 设置canvas大小
            canvas.width = 800;
            canvas.height = 800;
          }
        });
    },

    // 获取同住人详情
    getCohabitantDetail(renterId) {
      cohabitantDetail(renterId).then(res => {
        this.formData = res.data;
      })
    },
    
    // 打开底部操作表
    openPhotoActionSheet() {
      this.$refs.photoActionSheet.open();
    },
    
    // 关闭底部操作表
    closeActionSheet() {
      this.$refs.photoActionSheet.close();
    },
    
    // 拍照
    takePhoto() {
      uni.chooseImage({
        count: 1,
        sourceType: ['camera'],
        success: (res) => {
          this.handleImageSuccess(res);
        },
        fail: (err) => {
          uni.showToast({
            title: '拍照失败',
            icon: 'none'
          });
        },
        complete: () => {
          this.closeActionSheet();
        }
      });
    },
    
    // 从相册选择
    chooseFromAlbum() {
      uni.chooseImage({
        count: 1,
        sourceType: ['album'],
        success: (res) => {
          this.handleImageSuccess(res);
        },
        fail: (err) => {
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          });
        },
        complete: () => {
          this.closeActionSheet();
        }
      });
    },
    
    // 处理图片选择成功
    handleImageSuccess(res) {
      const tempFilePath = res.tempFilePaths[0];
      
      // 获取图片信息，检查大小
      uni.getFileInfo({
        filePath: tempFilePath,
        success: (fileInfo) => {
          console.log('原始图片大小：', fileInfo.size / 1024, 'KB');
          
          // 如果图片大于1MB，进行压缩
          if (fileInfo.size > this.imageCompressOptions.maxSize) {
            uni.showLoading({
              title: '图片压缩中...'
            });
            this.compressImage(tempFilePath, fileInfo.size);
          } else {
            // 图片小于1MB，直接使用
            this.formData.picUrl = tempFilePath;
          }
        },
        fail: (err) => {
          console.error('获取图片信息失败', err);
          uni.showToast({
            title: '获取图片信息失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 压缩图片
    compressImage(filePath, originalSize) {
      let quality = this.imageCompressOptions.quality;
      
      // 根据原始大小调整压缩质量
      if (originalSize > 5 * 1024 * 1024) { // 大于5MB
        quality = 0.6;
      } else if (originalSize > 3 * 1024 * 1024) { // 大于3MB
        quality = 0.7;
      }
      
      // 使用uni.compressImage进行压缩
      uni.compressImage({
        src: filePath,
        quality: quality * 100, // uni.compressImage需要0-100的质量值
        success: (res) => {
          // 获取压缩后的图片信息
          uni.getFileInfo({
            filePath: res.tempFilePath,
            success: (fileInfo) => {
              console.log('压缩后图片大小：', fileInfo.size / 1024, 'KB');
              
              // 如果压缩后仍然大于1MB，使用Canvas 2D进行尺寸压缩
              if (fileInfo.size > this.imageCompressOptions.maxSize) {
                this.compressImageByCanvas(res.tempFilePath);
              } else {
                // 压缩成功，大小符合要求
                this.formData.picUrl = res.tempFilePath;
                uni.hideLoading();
              }
            },
            fail: (err) => {
              console.error('获取压缩后图片信息失败', err);
              uni.hideLoading();
              uni.showToast({
                title: '图片处理失败',
                icon: 'none'
              });
            }
          });
        },
        fail: (err) => {
          console.error('压缩图片失败', err);
          // 如果uni.compressImage失败，尝试使用Canvas 2D压缩
          this.compressImageByCanvas(filePath);
        }
      });
    },
    
    // 使用Canvas 2D压缩图片
    compressImageByCanvas(filePath) {
      if (!this.canvasContext) {
        console.error('Canvas 2D上下文未初始化');
        uni.hideLoading();
        uni.showToast({
          title: '图片处理失败',
          icon: 'none'
        });
        return;
      }
      
      // 获取图片信息
      uni.getImageInfo({
        src: filePath,
        success: (imageInfo) => {
          // 计算新的尺寸，保持宽高比
          const maxWidth = 800;
          const maxHeight = 800;
          
          let newWidth = imageInfo.width;
          let newHeight = imageInfo.height;
          
          if (newWidth > maxWidth || newHeight > maxHeight) {
            if (newWidth / newHeight > 1) {
              // 宽图
              newWidth = maxWidth;
              newHeight = Math.floor(imageInfo.height * (maxWidth / imageInfo.width));
            } else {
              // 高图
              newHeight = maxHeight;
              newWidth = Math.floor(imageInfo.width * (maxHeight / imageInfo.height));
            }
          }
          
          // 创建图片对象
          const query = uni.createSelectorQuery().in(this);
          query.select('#compressCanvas')
            .fields({ node: true, size: true })
            .exec((res) => {
              if (res[0]) {
                const canvas = res[0].node;
                const ctx = this.canvasContext;
                
                // 清空画布
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                
                // 创建图片对象
                const img = canvas.createImage();
                img.onload = () => {
                  // 绘制图片到画布
                  ctx.drawImage(img, 0, 0, newWidth, newHeight);
                  
                  // 导出图片
                  uni.canvasToTempFilePath({
                    canvas: canvas,
                    width: newWidth,
                    height: newHeight,
                    destWidth: newWidth,
                    destHeight: newHeight,
                    fileType: 'jpg',
                    quality: 0.8,
                    success: (res) => {
                      // 检查压缩后的大小
                      uni.getFileInfo({
                        filePath: res.tempFilePath,
                        success: (fileInfo) => {
                          console.log('Canvas压缩后图片大小：', fileInfo.size / 1024, 'KB');
                          
                          if (fileInfo.size > this.imageCompressOptions.maxSize && newWidth > 400) {
                            // 如果还是太大，继续降低尺寸
                            this.compressImageByCanvas(res.tempFilePath);
                          } else {
                            this.formData.picUrl = res.tempFilePath;
                            uni.hideLoading();
                          }
                        },
                        fail: (err) => {
                          console.error('获取Canvas压缩后图片信息失败', err);
                          uni.hideLoading();
                          uni.showToast({
                            title: '图片处理失败',
                            icon: 'none'
                          });
                        }
                      });
                    },
                    fail: (err) => {
                      console.error('Canvas导出图片失败', err);
                      uni.hideLoading();
                      uni.showToast({
                        title: '图片处理失败',
                        icon: 'none'
                      });
                    }
                  }, this);
                };
                
                img.onerror = () => {
                  console.error('图片加载失败');
                  uni.hideLoading();
                  uni.showToast({
                    title: '图片处理失败',
                    icon: 'none'
                  });
                };
                
                // 设置图片源
                img.src = filePath;
              } else {
                console.error('未找到Canvas节点');
                uni.hideLoading();
                uni.showToast({
                  title: '图片处理失败',
                  icon: 'none'
                });
              }
            });
        },
        fail: (err) => {
          console.error('获取图片信息失败', err);
          uni.hideLoading();
          uni.showToast({
            title: '图片处理失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 提交表单
    submitForm() {
      this.$refs.form.validate().then(res => {
        // 表单验证通过
        uni.showLoading({
          title: '提交中...'
        });
          // 需要先上传图片
          uni.uploadFile({
            url: `${config.baseUrl}/file/upload`, // 替换为实际的上传接口地址
            filePath: this.formData.picUrl,
            name: 'file',
            header: {
              'Authorization': 'Bearer ' + getToken()
            },
            success: (uploadRes) => {
              try {
                const data = JSON.parse(uploadRes.data);
                if (data.code === 200 && data.data && data.data.url) {
                  // 上传成功，更新图片URL
                  this.formData.picUrl = data.data.url;
                  // 上传成功后调用人脸验证接口
                  this.submitFaceVerify();
                } else {
                  uni.hideLoading();
                  uni.showToast({
                    title: data.message || '图片上传失败',
                    icon: 'none',
                    duration: 2000
                  });
                }
              } catch (e) {
                uni.hideLoading();
                uni.showToast({
                  title: '图片上传失败，返回数据格式错误',
                  icon: 'none',
                  duration: 2000
                });
                console.error('解析上传响应失败:', e);
              }
            },
            fail: (err) => {
              uni.hideLoading();
              uni.showToast({
                title: '图片上传失败',
                icon: 'none',
                duration: 2000
              });
              console.error('图片上传失败:', err);
            }
          });
      }).catch(err => {
        console.log('表单错误：', err);
        
        // 显示第一个错误信息
        if (err && err.length > 0) {
          uni.showToast({
            title: err[0].errorMessage || '表单填写有误，请检查',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
    
    // 提交人脸验证
    submitFaceVerify() {
      faceVerify(this.formData).then(res => {
        if (res.code === 200) {
          uni.showToast({
            title: '认证成功',
            icon: 'success'
          });
          setTimeout(() => {
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 2];
            
            // 更新上一页的数据
            if (prevPage && prevPage.route.includes('cohabitant/detail')) {
              prevPage.$vm.formData.verifyStatus = 1;
              prevPage.$vm.formData.picUrl = this.formData.picUrl;
            }
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: res.message || '提交失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        uni.showToast({
          title: '提交失败',
          icon: 'none'
        });
        console.error('人脸验证失败:', err);
      }).finally(() => {
        uni.hideLoading();
      });
    },
    
  }
}
</script>

<style lang="scss">
.face-verify-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 30rpx;
  box-sizing: border-box;
  
  .page-header {
    text-align: center;
    padding: 40rpx 0;
    
    .page-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
      display: block;
      margin-bottom: 16rpx;
    }
    
    .page-desc {
      font-size: 26rpx;
      color: #666;
    }
  }
  
  .form-card {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
    margin-bottom: 40rpx;
    
    :deep(.uni-forms-item) {
      padding-bottom: 30rpx;
      margin-bottom: 10rpx;
      
      .uni-forms-item__label {
        font-size: 28rpx;
        font-weight: 500;
        color: #333;
        margin-bottom: 12rpx;
      }
      
      .uni-easyinput__content {
        height: 88rpx;
        background-color: #f8f9fc;
        border-radius: 8rpx;
        border: 1px solid #e5e7eb;
        
        &.is-input-border {
          border: 1px solid #e5e7eb;
          
          &:hover, &:focus {
            border-color: #3c9cff;
          }
        }
      }
    }
    
    .face-photo-wrapper {
      .face-photo-container {
        width: 240rpx;
        height: 240rpx;
        border: 1px dashed #d0d7de;
        border-radius: 12rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        overflow: hidden;
        background-color: #f8f9fc;
        transition: all 0.3s;
        
        &:active {
          background-color: #eef1f6;
        }
        
        .face-photo {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        
        .face-photo-placeholder {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          color: #999;
          
          .placeholder-text {
            font-size: 26rpx;
            margin-top: 16rpx;
            color: #666;
          }
        }
      }
      
      .photo-tip {
        font-size: 24rpx;
        color: #999;
        margin-top: 16rpx;
        display: block;
      }
    }
  }
  
  .submit-btn-container {
    padding: 0 20rpx;
    
    .submit-btn {
      width: 100%;
      height: 90rpx;
      line-height: 90rpx;
      font-size: 32rpx;
      font-weight: 500;
      border-radius: 45rpx;
      background: linear-gradient(to right, #3c9cff, #5dabff);
      box-shadow: 0 10rpx 20rpx rgba(60, 156, 255, 0.3);
      border: none;
    }
  }
}

.action-sheet {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  overflow: hidden;
  padding-bottom: env(safe-area-inset-bottom);
  
  .action-sheet-title {
    text-align: center;
    font-size: 28rpx;
    color: #999;
    padding: 20rpx 0;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .action-item {
    height: 110rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    color: #333;
    border-bottom: 1px solid #f0f0f0;
    
    uni-icons {
      margin-right: 10rpx;
    }
    
    &:active {
      background-color: #f8f8f8;
    }
    
    &.cancel {
      margin-top: 20rpx;
      color: #666;
      border-bottom: none;
    }
  }
}
</style>
